<?php
declare(strict_types=1);

namespace app\job;

use think\queue\Job;
use app\service\{MessageService, LogService};

class SendMessageJob
{
    public function fire(Job $job, $data)
    {
        try {
            $messageService = new MessageService();
            
            // 发送消息
            $result = $messageService->send(
                $data['merchant_id'],
                $data['user_id'],
                $data['template_id'],
                $data['params']
            );
            
            if ($result) {
                $job->delete();
                return;
            }
            
            // 失败重试
            if ($job->attempts() > 3) {
                LogService::error('SendMessageJob', sprintf(
                    'Send message failed after 3 retries: %s',
                    json_encode($data, JSON_UNESCAPED_UNICODE)
                ));
                $job->delete();
                return;
            }
            
            $job->release(3); // 延迟3秒重试
            
        } catch (\Exception $e) {
            LogService::error('SendMessageJob', sprintf(
                'Send message error: %s, data: %s',
                $e->getMessage(),
                json_encode($data, JSON_UNESCAPED_UNICODE)
            ));
            
            if ($job->attempts() > 3) {
                $job->delete();
                return;
            }
            
            $job->release(3);
        }
    }
} 